﻿using Castle.Core.Logging;
using System;
using Abp.Application.Services;
using Abp.Dependency;

namespace Abp.Configurations
{
    /// <summary>
    /// 配置：调用顺序依次为：Create().UseCastle().RegisterCommonComponents().UseLog4Net().RegisterUnhandledExceptionHandler().
    /// </summary>
    public class Configuration
    {
        /// <summary>Provides the singleton access instance.
        /// </summary>
        public static Configuration Instance { get; private set; }

       

        private Configuration() { }

        public static Configuration Create()
        {
            Instance = new Configuration();
           
            return Instance;
        }

        public Configuration SetDefault<TService, TImplementer>(string serviceName = null, LifeStyle life = LifeStyle.Singleton)
            where TService : class
            where TImplementer : class, TService
        {
            ObjectContainer.Register<TService, TImplementer>(serviceName, life);
            return this;
        }
        public Configuration SetDefault<TService, TImplementer>(TImplementer instance, string serviceName = null)
            where TService : class
            where TImplementer : class, TService
        {
            ObjectContainer.RegisterInstance<TService, TImplementer>(instance, serviceName);
            return this;
        }

        public Configuration RegisterCommonComponents()
        {
            SetDefault<IServiceManager, ServiceManagerImpl>();
            return this;
        }
        public Configuration RegisterUnhandledExceptionHandler()
        {
          
            AppDomain.CurrentDomain.UnhandledException += (sender, e) => {
                var logger = ObjectContainer.Resolve<ILogger>();
                logger.ErrorFormat("Unhandled exception: {0}", e.ExceptionObject);
            };
            return this;
        }
    }
}
